<?php

include 'common.php';
$conf['gpsserver'] = "paver.zjzd-tech.com/?s=ddc" ;


function datasync($db,$redis,$conf){

    while(1){

        if (time() % 60==0){
            syncInitData($conf, $db);
        } 

        $flag = getFlag($db);

        $sql= "select * from gpsinfo where id>".$flag['upload']." and sid=".$conf['sid']." limit 20";
		$data = $db->select($sql);
//	print_r($data);
//	exit;
        if(!$data){
            //continue;
        }
        $postData['sid'] = $conf['sid'];
        $postData['data'] = json_encode($data);
        $postData['lastid'] = $flag['download'];
        $url = 'http://'.$conf['gpsserver'];
        // print_r($postData);
        // exit;
        // echo "\n\r".date('Y-m-d H:i:s ').'Send:'.json_encode($postData);
        $start_time  = microtime();
        $res = curlPost($url, $postData);
        $end_time = microtime();

        echo "\n\r".date('Y-m-d H:i:s ').'Resp:'.$res;
		if(!$res){
			 $left_time = 999;
			 $redis->setex('network',30,$left_time);
			 continue;
		}
        
        $resData = json_decode($res, true);
        $nowtime = date('Y-m-d H:i:s');
        //如果接受成功,更新上传ID标志
        if($data && $resData['status']){
        	$left_time = round(($end_time-$start_time)*100);
        	if($left_time>0) $redis->setex('network',25,$left_time);
            $updata_end = end($data);
            echo "\n\r$nowtime upload success ".$updata_end['id']." \n\r";
            $flag['upload'] = $updata_end['id'];
            $sql = "update flag set val=".$flag['upload'].",update_time='$nowtime' where flag='upload'";
            $db->query($sql) ;
        }

        //var_dump($resData);
        //如果有返回其他设备数据,则插入

        $devices=[];
        if($resData['status']==2){
            $down_id =0;
            foreach($resData['data'] as $k=>$v){
                $down_id=$v['id'];
                unset($v['id']);
                $db->insert('gpsinfo',$v);
                //获取每个设备的 经纬度
                $devices[$v['sid']] =$v;
            }
            
	   		$deviceList = $resData['carlist'];	
            //更新每个设备的经纬度
            foreach($deviceList as $k=>$v){
            	 $v['temperature'] = $v['tmp'];
            	 unset($v['tmp']);
            	 $sid=$v['id'];
            	 unset($v['id']);
                $db->update('carlist',$v,'sid='.$sid,1);
            }
		
            if($down_id>0){

	            $sql = "update flag set val=".$down_id.",update_time='$nowtime' where flag='download'";
	            $db->query($sql);
	            echo "\n\r$nowtime download ".$down_id."\n\r";
		    }
        }

        sleep(1);
    }

}

datasync($db,$redisc,$conf);
